home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 15834 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: news.rchland.ibm.com!usenet
  2. From: Philip Staite <pstaite+@rchland.ibm.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Binary Converter
  5. Date: Mon, 08 Apr 1996 07:23:05 -0500
  6. Organization: IBM Rochester, MN
  7. Message-ID: <31690529.41C6@rchland.ibm.com>
  8. References: <31618729.6BC22935@oberon.hs.gettysburg.edu> <828744431snz@j-bg.demon.co.uk>
  9. NNTP-Posting-Host: powertool.rchland.ibm.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.01 (X11; I; AIX 1)
  14.  
  15. John Sargent wrote:
  16. > In article <31618729.6BC22935@oberon.hs.gettysburg.edu>  ** none **   writes:
  17. > > I am working on a binary converter function, and it isn't working
  18. > > correctly.  I am basically passing a number to be converted to the
  19. > > function, then using if statements to see which place of the number
  20. > > would be in, dividing, and then doing the same with the remainder, until
  21. > > the ones place.  Each time the number fits one of the if statements, it
  22. > > copies a one to a string, and for every if it does not fit, it copies a
  23. > > zero. Lastly it returns the converted binary number.  Does anyone know a
  24. > > better way of doing this?  Or why mine would not be working (I would
  25. > > include the source here, but I had some trouble, and had to reformat my
  26. > > drive, so it is gone as of now).  If you can help, please email me at
  27. > > mnicastr@oberon.hs.gettysburg.edu
  28. > > Thanks
  29. > void ToBin(unsigned int in, char * out)
  30. > {
  31. >     unsigned mask = 0x8000;
  32. >     int bit;
  33. >     *out = 0;
  34. >     for ( bit = 0; bit < 16; bit++)
  35. >     {
  36. >         if ( in & mask )
  37. >             strcat(out, "1");
  38. >         else
  39. >             strcat(out, "0");
  40. >         mask = mask >> 1;
  41. >     }
  42. > }
  43.  
  44. How about this version, which is independent of the size of ints...
  45.  
  46.  
  47. void ToBin( unsigned i, char* s ) {
  48.     for( unsigned m = 1 << ( sizeof(unsigned) * 8 - 1 ) ; m ; m >>= 1 )
  49.         *s++ = m & i ? '1' : '0';
  50.     *s = '\0'; }
  51.  
  52.  
  53.  
  54.  
  55.  
  56. -- 
  57.  
  58. Phil Staite, (507) 253-2529, team OS/2
  59. internet: pstaite@vnet.ibm.com  internal: pstaite@rchland
  60.